import { Feature } from "./jsonParser";

export default class Senen {
  private BASE_RATIO = 1000;
  private SCALE = {
    x: 0.08,
    y: 0.07,
  };
  private TRANSFORM = {
    x: 483500,
    y: 3538000,
  };
  private scale = 1;

  public ctx: CanvasRenderingContext2D | null;
  constructor(private cvs, private CANVAS_SIZE, private checkedGroup, private colors) {
    // 490301.4643327,
    // 3543180.6449501,
    cvs.width = this.CANVAS_SIZE * 0.9 * devicePixelRatio;
    cvs.height = this.CANVAS_SIZE * 0.9 * devicePixelRatio;
    this.cvs = cvs;
    // cvs.addEventListener('mousewheel', handleScroll);
    const ctx = cvs.getContext("2d");
    this.ctx = ctx;
    if (!ctx) return;

    ctx.fillStyle = "red";
  }

  // handleScroll(event) {
  //   // 阻止默认的滚轮行为，避免页面滚动
  //   event.preventDefault();

  //   const delta = Math.sign(event.deltaY);
  //   if (delta === 1) {
  //     this.scale *= 1.1;
  //   } else if (delta === -1) {
  //     this.scale /= 1.1;
  //   }
  //   this.ctx && this.updateCanvas(features);
  // }

  transform(coord: number[]) {
    const [x, y] = coord;
    const { TRANSFORM, SCALE, CANVAS_SIZE, BASE_RATIO } = this;

    // return [x / BASE_RATIO, y / BASE_RATIO];
    return [
      (x - TRANSFORM.x) * SCALE.x,
      CANVAS_SIZE - (y - TRANSFORM.y) * SCALE.y,
    ];
  }

  updateCanvas(features: any) {
    const scale = this.scale;
    const ctx = this.ctx!;
    ctx.clearRect(0, 0, this.cvs.width, this.cvs.height);
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    const render = (coord: number[], key: string) => {
      ctx.beginPath();
      const color = this.colors[key];
      ctx.strokeStyle = color;
      const [x, y] = this.transform(coord);
      ctx.moveTo(x, y);
      ctx.arc(x, y, 1, 0, Math.PI * 2);
      ctx.stroke();
    };
    this.checkedGroup.value.forEach((key) => {
      features[key].forEach((feature: Feature) => {
        if (feature.geometry.coordinates.length) {
          if (Array.isArray(feature.geometry.coordinates[0])) {
            feature.geometry.coordinates.forEach((coord) =>
              render(coord as number[], key)
            );
          } else {
            render(feature.geometry.coordinates as number[], key);
          }
        }
      });
    });
  }
}